import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Solitudefire
 * Date: 2022-08-01
 * Time: 16:08
 */
public class TestHeap {
    public int[] elem;
    public int UsedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    /**
     * 向下调整函数的实现
     *
     * @param parent 每棵树的根节点
     * @param len    每棵树的调整的结束位置
     */

    public void shiftDown(int parent, int len) {
        int child = 2 * parent + 1;
        //最起码是有左孩子的，至少有一个孩子
        while (child < len) {
            if (child + 1 < len && elem[child] < elem[child + 1]) {
                child++;//保证当前左右孩子最大值的下标
            }
            if (elem[parent] < elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    public void createBigHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            UsedSize++;
        }
        //根据代码 显示的时间复杂度  看起来应该是O(n*logn) 但是实际上是O(n)
        for (int parent = (UsedSize - 2) / 2; parent >= 0; parent--) {
            //调整
            shiftDown(parent, UsedSize);
        }

    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[parent] < elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public void offer(int val) {
        if (isFull()) {
            //扩容
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[UsedSize++] = val;
        //注意这里传入的是UsedSize-1
        shiftUp(UsedSize - 1);
    }

    public boolean isFull() {
        return UsedSize == elem.length;
    }

    public int poll() {
        if (isEmpty()) {
            throw new RuntimeException("优先级队列为空！");
        }
        int tmp = elem[0];
        elem[0] = elem[UsedSize - 1];
        elem[UsedSize - 1] = tmp;
        UsedSize--;
        shiftDown(0, UsedSize);
        return tmp;
    }

    public boolean isEmpty() {
        return UsedSize == 0;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("优先级队列为空！");
        }
        return elem[0];
    }

    public void heapSort() {
        int end = UsedSize - 1;
        while (end > 0) {
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0, end);
            end--;
        }
    }
}
